package com.yidingdui.service.impl;

import com.yidingdui.domain.vo.ModelHistoryVO;
import com.yidingdui.service.CacheService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class CacheServiceImpl implements CacheService {
    
    private final RedisTemplate<String, Object> redisTemplate;
    
    private static final String USER_HISTORY_KEY = "user:history:";
    private static final String TASK_STATUS_KEY = "task:status:";
    private static final String TASK_NOTIFICATION_CHANNEL = "task:notification";
    
    // 缓存过期时间：30分钟
    private static final Duration CACHE_EXPIRE = Duration.ofMinutes(30);
    
    @Override
    public void cacheUserHistory(Long userId, List<ModelHistoryVO> histories) {
        try {
            String key = USER_HISTORY_KEY + userId;
            redisTemplate.opsForValue().set(key, histories, CACHE_EXPIRE);
            log.debug("缓存用户历史记录: userId={}, count={}", userId, histories.size());
        } catch (Exception e) {
            log.error("缓存用户历史记录失败: userId={}", userId, e);
        }
    }
    
    @Override
    @SuppressWarnings("unchecked")
    public List<ModelHistoryVO> getUserHistoryFromCache(Long userId) {
        try {
            String key = USER_HISTORY_KEY + userId;
            Object cached = redisTemplate.opsForValue().get(key);
            if (cached instanceof List) {
                log.debug("从缓存获取用户历史记录: userId={}", userId);
                return (List<ModelHistoryVO>) cached;
            }
        } catch (Exception e) {
            log.error("从缓存获取用户历史记录失败: userId={}", userId, e);
        }
        return null;
    }
    
    @Override
    public void clearUserHistoryCache(Long userId) {
        try {
            String key = USER_HISTORY_KEY + userId;
            redisTemplate.delete(key);
            log.debug("清除用户历史记录缓存: userId={}", userId);
        } catch (Exception e) {
            log.error("清除用户历史记录缓存失败: userId={}", userId, e);
        }
    }
    
    @Override
    public void cacheTaskStatus(String taskId, ModelHistoryVO task) {
        try {
            String key = TASK_STATUS_KEY + taskId;
            redisTemplate.opsForValue().set(key, task, CACHE_EXPIRE);
            log.debug("缓存任务状态: taskId={}, status={}", taskId, task.getStatus());
        } catch (Exception e) {
            log.error("缓存任务状态失败: taskId={}", taskId, e);
        }
    }
    
    @Override
    public ModelHistoryVO getTaskStatusFromCache(String taskId) {
        try {
            String key = TASK_STATUS_KEY + taskId;
            Object cached = redisTemplate.opsForValue().get(key);
            if (cached instanceof ModelHistoryVO) {
                log.debug("从缓存获取任务状态: taskId={}", taskId);
                return (ModelHistoryVO) cached;
            }
        } catch (Exception e) {
            log.error("从缓存获取任务状态失败: taskId={}", taskId, e);
        }
        return null;
    }
    
    @Override
    public void clearTaskStatusCache(String taskId) {
        try {
            String key = TASK_STATUS_KEY + taskId;
            redisTemplate.delete(key);
            log.debug("清除任务状态缓存: taskId={}", taskId);
        } catch (Exception e) {
            log.error("清除任务状态缓存失败: taskId={}", taskId, e);
        }
    }
    
    @Override
    public void publishTaskCompletion(String taskId, String status, String message) {
        try {
            String notification = String.format("任务 %s 状态更新: %s - %s", taskId, status, message);
            redisTemplate.convertAndSend(TASK_NOTIFICATION_CHANNEL, notification);
            log.info("发布任务完成通知: taskId={}, status={}", taskId, status);
        } catch (Exception e) {
            log.error("发布任务完成通知失败: taskId={}", taskId, e);
        }
    }
}
